package com.supermarket.controller;

import cn.hutool.core.lang.intern.InternUtil;
import cn.hutool.core.util.StrUtil;
import com.supermarket.common.ResponseResult;
import com.supermarket.entity.DTO.OrderDTO;
import com.supermarket.entity.DTO.OrderItemDTO;
import com.supermarket.entity.Order;
import com.supermarket.entity.OrderDelivery;
import com.supermarket.entity.OrderItem;
import com.supermarket.entity.OrderPayment;
import com.supermarket.service.OrderDeliveryService;
import com.supermarket.service.OrderItemService;
import com.supermarket.service.OrderPaymentService;
import com.supermarket.service.OrderService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private OrderDeliveryService orderDeliveryService;

    @Resource
    private OrderPaymentService orderPaymentService;

    /**
     * 创建订单
     *
     * @param orderMap 包含订单信息和订单项的Map
     * @param session 会话信息
     * @return 订单创建结果
     */
    @PostMapping("/create")
    public ResponseResult<Map<String, Object>> createOrder(@RequestBody Map<String, Object> orderMap, HttpSession session) {
        try {
            // 检查用户是否登录
            if (session.getAttribute("currentUser") == null) {
                return ResponseResult.error(401, "请先登录");
            }

            // 解析订单基本信息
            Map<String, Object> orderInfo = (Map<String, Object>) orderMap.get("order");
            List<Map<String, Object>> itemsInfo = (List<Map<String, Object>>) orderMap.get("items");

            if (orderInfo == null || itemsInfo == null || itemsInfo.isEmpty()) {
                return ResponseResult.error(400, "订单信息不完整");
            }

            // 创建订单对象
            Order order = new Order();
            order.setUserId((Integer) orderInfo.get("userId"));
            order.setAddressId((Integer) orderInfo.get("addressId"));
            order.setPaymentType((String) orderInfo.get("paymentType"));
            order.setTotalAmount(new java.math.BigDecimal(orderInfo.get("totalAmount").toString()));
            order.setActualAmount(new java.math.BigDecimal(orderInfo.get("actualAmount").toString()));
            order.setRemark((String) orderInfo.get("remark"));
            
            // 判断是否为货到付款，如果是则直接设置为已付款状态
            Boolean isPaidDirectly = (Boolean) orderInfo.get("isPaidDirectly");
            if (isPaidDirectly != null && isPaidDirectly) {
                order.setStatus("PAID");
                order.setPaymentTime(new Date());
            }

            // 创建订单项列表
            List<OrderItem> orderItems = new ArrayList<>();
            for (Map<String, Object> item : itemsInfo) {
                OrderItem orderItem = new OrderItem();
                orderItem.setCommodityId((Integer) item.get("commodityId"));
                orderItem.setCommodityName((String) item.get("commodityName"));
                orderItem.setCommodityPrice(new java.math.BigDecimal(item.get("commodityPrice").toString()));
                orderItem.setQuantity((Integer) item.get("quantity"));
                orderItem.setSubtotal(new java.math.BigDecimal(item.get("subtotal").toString()));
                orderItems.add(orderItem);
            }

            // 创建订单
            Order createdOrder = orderService.createOrder(order, orderItems);

            // 创建配送信息
            OrderDelivery orderDelivery = new OrderDelivery();
            orderDelivery.setOrderId(createdOrder.getId());
            orderDeliveryService.createOrderDelivery(orderDelivery);

            // 创建支付信息
            OrderPayment orderPayment = new OrderPayment();
            orderPayment.setOrderId(createdOrder.getId());
            orderPayment.setPaymentAmount(createdOrder.getActualAmount());
            orderPayment.setPaymentStatus("PENDING");
            orderPaymentService.createOrderPayment(orderPayment);

            // 返回订单信息
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", createdOrder.getId());
            result.put("orderNo", createdOrder.getOrderNo());
            result.put("status", createdOrder.getStatus());
            return ResponseResult.success(result);
        } catch (Exception e) {
            return ResponseResult.error(500, "创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 查询订单列表
     *
     * @param status 订单状态（可选）
     * @param session HttpSession
     * @return 订单列表
     */
    @GetMapping("/list")
    public ResponseResult<List<OrderDTO>> getOrderList(
            @RequestParam(required = false) String status,
            HttpSession session) {
        try {
            // 从会话中获取用户ID
            Object userObj = session.getAttribute("currentUser");
            if (userObj == null) {
                return ResponseResult.error(401, "请先登录");
            }
            
            // 获取用户ID
            Integer userId = ((com.supermarket.entity.User) userObj).getId();
            
            List<OrderDTO> orders;
            if (status != null && !status.isEmpty()) {
                orders = orderService.getOrdersByUserIdAndStatus(userId, status);
                // 查询订单商品项明细
                for (OrderDTO order : orders) {
                    List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                    order.setOrderItems(orderItems);
                }
            } else {
                orders = orderService.getOrdersByUserId(userId);
                // 查询订单商品项明细
                for (OrderDTO order : orders) {
                    List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                    order.setOrderItems(orderItems);
                }
            }
            return ResponseResult.success(orders);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询订单失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     *
     * @param orderNo 订单编号
     * @return 订单详情
     */
    @GetMapping("/detail/{orderNo}")
    public ResponseResult<Map<String, Object>> getOrderDetail(@PathVariable String orderNo) {
        try {
            // 查询订单基本信息
            OrderDTO order = orderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                return ResponseResult.error(404, "订单不存在");
            }

            // 查询订单商品明细
            List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
            
            // 计算商品总数量
            int itemCount = 0;
            if (orderItems != null) {
                for (OrderItemDTO item : orderItems) {
                    itemCount += item.getQuantity();
                }
            }
            order.setItemCount(itemCount);

            // 查询订单配送信息
            OrderDelivery orderDelivery = orderDeliveryService.getOrderDeliveryByOrderId(order.getId());

            // 查询订单支付信息
            OrderPayment orderPayment = orderPaymentService.getOrderPaymentByOrderId(order.getId());

            // 组装结果
            Map<String, Object> result = new HashMap<>();
            result.put("order", order);
            result.put("items", orderItems);
            result.put("delivery", orderDelivery);
            result.put("payment", orderPayment);

            return ResponseResult.success(result);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 取消订单
     *
     * @param orderNo 订单编号
     * @return 操作结果
     */
    @PutMapping("/cancel/{orderNo}")
    public ResponseResult<String> cancelOrder(@PathVariable String orderNo) {
        try {
            boolean result = orderService.cancelOrder(orderNo);
            if (result) {
                return ResponseResult.success("订单取消成功");
            } else {
                return ResponseResult.error(400, "订单取消失败，可能已支付或已取消");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "取消订单失败: " + e.getMessage());
        }
    }

    /**
     * 支付订单
     *
     * @param paymentMap 支付信息
     * @return 操作结果
     */
    @PutMapping("/pay")
    public ResponseResult<Map<String, Object>> payOrder(@RequestBody Map<String, Object> paymentMap) {
        System.out.println("PaymentMap: " + paymentMap);
        try {
            Integer orderId = orderService.getOrderByOrderNo(paymentMap.get("orderId").toString()).getId();
            String paymentNo = StrUtil.toString(paymentMap.get("paymentNo"));
            String paymentPlatform = (String) paymentMap.get("paymentPlatform");

            // 更新订单状态为已支付
            boolean orderPaid = orderService.payOrder(orderId);
            if (!orderPaid) {
                return ResponseResult.error(400, "订单支付失败，订单可能已支付或已取消");
            }

            // 更新支付信息
            OrderPayment payment = orderPaymentService.getOrderPaymentByOrderId(orderId);
            payment.setPaymentNo(paymentNo);
            payment.setPaymentPlatform(paymentPlatform);
            payment.setPaymentStatus("SUCCESS");
            payment.setPaymentTime(new Date());
            orderPaymentService.updateOrderPayment(payment);

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", orderId);
            result.put("paymentStatus", "SUCCESS");
            result.put("paymentTime", payment.getPaymentTime());
            return ResponseResult.success(result);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResponseResult.error(500, "支付订单失败: " + e.getMessage());
        }
    }

    /**
     * 发货
     *
     * @param shippingMap 发货信息
     * @return 操作结果
     */
    @PutMapping("/ship")
    public ResponseResult<String> shipOrder(@RequestBody Map<String, Object> shippingMap) {
        try {
            Integer orderId = (Integer) shippingMap.get("orderId");
            Integer riderId = (Integer) shippingMap.get("riderId");

            // 更新订单状态为已发货
            boolean orderShipped = orderService.shipOrder(orderId);
            if (!orderShipped) {
                return ResponseResult.error(400, "订单发货失败，订单可能未支付或已发货");
            }

            // 更新配送信息
            OrderDelivery delivery = orderDeliveryService.getOrderDeliveryByOrderId(orderId);
            if (delivery != null) {
                // 分配骑手
                orderDeliveryService.assignRider(delivery.getId(), riderId);
                return ResponseResult.success("订单发货成功");
            } else {
                return ResponseResult.error(404, "配送信息不存在");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "订单发货失败: " + e.getMessage());
        }
    }

    /**
     * 确认收货（完成订单）
     * 根据参数类型自动判断是订单ID还是订单编号
     *
     * @param orderIdentifier 订单ID或订单编号
     * @return 操作结果
     */
    @PutMapping("/complete/{orderIdentifier}")
    public ResponseResult<String> completeOrder(@PathVariable String orderIdentifier) {
        try {
            Integer orderId = null;
            
            // 尝试将参数解析为Integer，判断是否为订单ID
            try {
                orderId = Integer.parseInt(orderIdentifier);
            } catch (NumberFormatException e) {
                // 非数字，则视为订单编号
                OrderDTO order = orderService.getOrderByOrderNo(orderIdentifier);
                if (order == null) {
                    return ResponseResult.error(404, "订单不存在");
                }
                orderId = order.getId();
            }
            
            boolean result = orderService.completeOrder(orderId);
            if (result) {
                // 更新配送信息为已送达
                OrderDelivery delivery = orderDeliveryService.getOrderDeliveryByOrderId(orderId);
                if (delivery != null) {
                    orderDeliveryService.updateToDeliveredStatus(delivery.getId());
                }
                return ResponseResult.success("订单完成成功");
            } else {
                return ResponseResult.error(400, "订单完成失败，订单可能未发货或已完成");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "完成订单失败: " + e.getMessage());
        }
    }

    /**
     * 评价骑手
     *
     * @param ratingMap 评价信息
     * @return 操作结果
     */
    @PutMapping("/rate-rider")
    public ResponseResult<String> rateRider(@RequestBody Map<String, Object> ratingMap) {
        try {
            Integer orderId = (Integer) ratingMap.get("orderId");
            Integer rating = (Integer) ratingMap.get("rating");
            String comment = (String) ratingMap.get("comment");

            OrderDelivery delivery = orderDeliveryService.getOrderDeliveryByOrderId(orderId);
            if (delivery == null) {
                return ResponseResult.error(404, "配送信息不存在");
            }

            boolean result = orderDeliveryService.rateRider(delivery.getId(), rating, comment);
            if (result) {
                return ResponseResult.success("评价成功");
            } else {
                return ResponseResult.error(400, "评价失败，订单可能未完成或骑手未分配");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "评价骑手失败: " + e.getMessage());
        }
    }

    /**
     * 查询待付款订单
     *
     * @param session HttpSession
     * @return 待付款订单列表
     */
    @GetMapping("/pending-payment")
    public ResponseResult<List<OrderDTO>> getPendingPaymentOrders(HttpSession session) {
        try {
            // 从会话中获取用户ID
            Object userObj = session.getAttribute("currentUser");
            if (userObj == null) {
                return ResponseResult.error(401, "请先登录");
            }
            
            // 获取用户ID
            Integer userId = ((com.supermarket.entity.User) userObj).getId();
            
            List<OrderDTO> orders = orderService.getOrdersByUserIdAndStatus(userId, "PENDING_PAYMENT");
            // 查询订单商品项明细
            for (OrderDTO order : orders) {
                List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                order.setOrderItems(orderItems);
            }
            return ResponseResult.success(orders);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询待付款订单失败: " + e.getMessage());
        }
    }

    /**
     * 查询待发货订单
     *
     * @param session HttpSession
     * @return 待发货订单列表
     */
    @GetMapping("/paid")
    public ResponseResult<List<OrderDTO>> getPaidOrders(HttpSession session) {
        try {
            // 从会话中获取用户ID
            Object userObj = session.getAttribute("currentUser");
            if (userObj == null) {
                return ResponseResult.error(401, "请先登录");
            }
            
            // 获取用户ID
            Integer userId = ((com.supermarket.entity.User) userObj).getId();
            
            List<OrderDTO> orders = orderService.getOrdersByUserIdAndStatus(userId, "PAID");
            // 查询订单商品项明细
            for (OrderDTO order : orders) {
                List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                order.setOrderItems(orderItems);
            }
            return ResponseResult.success(orders);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询待发货订单失败: " + e.getMessage());
        }
    }

    /**
     * 查询配送中订单
     *
     * @param session HttpSession
     * @return 配送中订单列表
     */
    @GetMapping("/shipped")
    public ResponseResult<List<OrderDTO>> getShippedOrders(HttpSession session) {
        try {
            // 从会话中获取用户ID
            Object userObj = session.getAttribute("currentUser");
            if (userObj == null) {
                return ResponseResult.error(401, "请先登录");
            }
            
            // 获取用户ID
            Integer userId = ((com.supermarket.entity.User) userObj).getId();
            
            List<OrderDTO> orders = orderService.getOrdersByUserIdAndStatus(userId, "SHIPPED");
            // 查询订单商品项明细
            for (OrderDTO order : orders) {
                List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                order.setOrderItems(orderItems);
            }
            return ResponseResult.success(orders);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询配送中订单失败: " + e.getMessage());
        }
    }

    /**
     * 查询已完成订单
     *
     * @param session HttpSession
     * @return 已完成订单列表
     */
    @GetMapping("/completed")
    public ResponseResult<List<OrderDTO>> getCompletedOrders(HttpSession session) {
        try {
            // 从会话中获取用户ID
            Object userObj = session.getAttribute("currentUser");
            if (userObj == null) {
                return ResponseResult.error(401, "请先登录");
            }
            
            // 获取用户ID
            Integer userId = ((com.supermarket.entity.User) userObj).getId();
            
            List<OrderDTO> orders = orderService.getOrdersByUserIdAndStatus(userId, "COMPLETED");
            // 查询订单商品项明细
            for (OrderDTO order : orders) {
                List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                order.setOrderItems(orderItems);
            }
            return ResponseResult.success(orders);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询已完成订单失败: " + e.getMessage());
        }
    }

    /**
     * 查询已取消订单
     *
     * @param session HttpSession
     * @return 已取消订单列表
     */
    @GetMapping("/cancelled")
    public ResponseResult<List<OrderDTO>> getCancelledOrders(HttpSession session) {
        try {
            // 从会话中获取用户ID
            Object userObj = session.getAttribute("currentUser");
            if (userObj == null) {
                return ResponseResult.error(401, "请先登录");
            }
            
            // 获取用户ID
            Integer userId = ((com.supermarket.entity.User) userObj).getId();
            
            List<OrderDTO> orders = orderService.getOrdersByUserIdAndStatus(userId, "CANCELLED");
            // 查询订单商品项明细
            for (OrderDTO order : orders) {
                List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                order.setOrderItems(orderItems);
            }
            return ResponseResult.success(orders);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询已取消订单失败: " + e.getMessage());
        }
    }

    /**
     * 根据条件分页查询订单（后台管理用）
     *
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param status 订单状态（可选）
     * @param orderNo 订单编号（可选）
     * @return 订单列表和总数
     */
    @GetMapping("/status")
    public ResponseResult<Map<String, Object>> getOrdersByCondition(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String orderNo) {
        try {
            Map<String, Object> result = orderService.getOrdersWithCondition(status, orderNo, pageNum, pageSize);
            
            // 查询每个订单的商品明细
            List<OrderDTO> orders = (List<OrderDTO>) result.get("list");
            if (orders != null) {
                for (OrderDTO order : orders) {
                    List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(order.getId());
                    order.setOrderItems(orderItems);
                    
                    // 计算商品总数量
                    int itemCount = 0;
                    if (orderItems != null) {
                        for (OrderItemDTO item : orderItems) {
                            itemCount += item.getQuantity();
                        }
                    }
                    order.setItemCount(itemCount);
                }
            }
            
            return ResponseResult.success(result);
        } catch (Exception e) {
            return ResponseResult.error(500, "查询订单列表失败: " + e.getMessage());
        }
    }
}
